/* eslint-disable max-lines */
import * as BASE from '@/stores/definitions-base';
import { Divider, Input, Switch } from '@alifd/next';
import { t } from '@lingui/macro';
import React from 'react';
import { ellipsisRender } from '@/components/TauTable';
import TauSimpleSelect from '@/components/TauSimpleSelect';

const {
  DATETIME_TEXT,
  DATE_TEXT,
  TIME_TEXT,
  EMPTY_TEXT,
  ENUMS: ENUMSBase,
  FieldsGrid: FieldGridBase,
  TitleGrid,
  column: columnBase,
  toSelectDataSource,
} = BASE;
export { DATETIME_TEXT, DATE_TEXT, EMPTY_TEXT, TIME_TEXT, TitleGrid, toSelectDataSource };

export function column(...args) {
  return columnBase(orderModel, ...args);
}

export function FieldsGrid(props) {
  return <FieldGridBase model={orderModel} {...props} />;
}

//----------------------------------------------------------------------
export const ENUMS = {
  ...ENUMSBase,
  states: {
    0: t`已取消`,
    1: t`待派车`,
    2: t`进行中`,
    3: t`已完成`,
  },
  _dispatch_states: {
    2: t`进行中`,
    3: t`已完成`,
  },
  ticketState: {
    0: t`未乘车`,
    1: t`已乘车`,
  },
};

export const orderModel = {
  orderBaseModel: {
    label: t`订单相关信息`,
    flightNumber: {
      label: t`航班号`,
    },
    orderType: {
      label: t`订单类型，0 - 点对点；1 - 时租`,
    },
    vehicleId: {
      label: t`车辆id`,
    },
    driverId: {
      label: t`司机id`,
    },
    driverName: {
      label: t`司机名`,
    },
    language: [
      {
        label: t`语言要求`,
      },
    ],
    passengerName: {
      label: t`乘坐人`,
    },
    passengerPhone: {
      label: t`乘坐人电话`,
    },
    subscribeName: {
      label: t`预约人`,
    },
    subscribePhone: {
      label: t`预约人电话`,
    },
    number: {
      label: t`人数`,
    },
    numberOfLuggage: {
      label: t`行李数`,
    },
    startMainArea: {
      label: t`开始城市编号`,
    },
    startMinorArea: {
      label: t`开始区域编号`,
    },
    startStationName: {
      label: t`开始站点名称`,
    },
    endMainArea: {
      label: t`结束城市编号`,
    },
    endMinorArea: {
      label: t`结束区域编号`,
    },
    endStationName: {
      label: t`结束站点名称`,
    },
    predictBeginDate: {
      label: t`预估开始时间`,
    },
    predictEndDate: {
      label: t`预估结束时间`,
    },
    isPass: {
      label: t`是否过关`,
    },
    portType: {
      label: t`口岸类型，0 - 深圳湾口岸；1 - 澳门口岸；2 - 珠海口岸`,
    },
    isMap: {
      label: t`需要地图链接`,
    },
    predictTime: {
      label: t`预估时长`,
    },
    mileage: {
      label: t`里程`,
    },
    beginName: {
      label: t`开始地址`,
      ui: {
        span: 2,
      },
    },
    beginTude: {
      label: t`开始地址经纬度`,
    },
    endName: {
      label: t`结束地址`,
      ui: {
        span: 2,
      },
    },
    endTude: {
      label: t`结束地址经纬度`,
    },
    surcharges: [
      {
        label: t`附加费列表`,
      },
    ],
    roadFee: {
      label: t`路桥费`,
    },
    oilFee: {
      label: t`加油费`,
    },
    partFee: {
      label: t`停车费`,
    },
    repairFee: {
      label: t`维修费`,
    },
    otherFee: {
      label: t`其他费用`,
    },
    surchargeExplain: {
      label: t`附加费说明`,
    },
    addFee: {
      label: t`附加总费用`,
    },
    surchargePayStatus: {
      label: t`附加费支付状态，0 - 未支付；1 - 已支付；`,
    },
    surchargePayUrl: {
      label: t`附加费微信支付地址`,
    },
    portTypeText: {
      label: t`口岸`,
    },
    startMainAreaText: {
      label: t`开始城市`,
    },
    endMainAreaText: {
      label: t`结束城市`,
    },
  },
  driverInfo: [
    {
      label: t`相关司机信息`,
      number: {
        label: t`工单id`,
      },
      licenseNo: {
        label: t`车牌编号`,
      },
      vehicle: {
        label: t`承运车辆`,
      },
      driverId: {
        label: t`司机id`,
      },
      name: {
        label: t`承运司机`,
      },
      phone: {
        label: t`司机电话`,
      },
      state: {
        label: t`司机状态 0-取消 1-已派车 2-司机已出发 3-接到乘客/开始上客 4-行程已开始 5-行程已结束`,
      },
      remark: {
        label: t`取消备注`,
      },
    },
  ],
  number: {
    label: t`任务编号 BCRW+yyyyMMdd+0001 ZXRW+yyyyMMdd+0001`,
  },
  orderIds: [
    {
      label: t`相关订单集合`,
    },
  ],
  state: {
    label: t`状态`,
    text: (v) => ENUMS.states[v],
    //  0-已取消 1-待派车 2-进行中 3-已完成`,
  },
  departureTime: {
    label: t`出发时间`,
    text: DATETIME_TEXT,
  },
  taskType: {
    label: t`任务类型 0：包车任务，1：专线任务`,
  },
  carrierCompany: {
    label: t`承运公司`,
  },
  dispatcher: {
    label: t`调度员`,
  },
  dispatcherName: {
    label: t`调度员名称`,
  },
  carrierCompanyName: {
    label: t`承运公司`,
  },
  carrierPrice: {
    label: t`公司价格`,
  },
  totalPrice: {
    label: t`任务总价`,
    ui: {
      renderer: (v) => {
        let text = 0;
        if (v !== null && v !== undefined) {
          text = v;
        }
        return <span>{text.toFixed(2)}</span>;
      },
    },
  },
  negotiatedPrice: {
    label: t`协议价格`,
  },
  remark: {
    label: t`派车备注`,
    ui: {
      renderer: (v) => <Input.TextArea value={v} placeholder={t`给司机留言`} />,
      span: 4,
    },
    ui_edit: {
      renderer: (v) => <Input.TextArea value={v} placeholder={t`给司机留言`} />,
      span: 4,
    },
  },
  dispatchOrderRemarks: {
    label: t`派单备注`,
    ui: {
      renderer: (v) => <Input.TextArea value={v} placeholder={t`给公司调度留言`} />,
      span: 4,
    },
  },
  dispatchRemarks: {
    label: t`未备案司机信息`,
    ui: {
      renderer: (v) => <Input.TextArea value={v} />,
      span: 4,
    },
    ui_edit: {
      renderer: (v) => <Input.TextArea value={v} />,
      span: 4,
    },
  },
  cancelRemark: {
    label: t`取消原因`,
    ui: {
      span: 4,
    },
    ui_edit: {
      renderer: (v) => <Input.TextArea value={v} />,
      span: 4,
    },
  },
  driverServiceFee: {
    label: t`司机服务费`,
  },
  midwayFee: {
    label: t`中途费用`,
  },
  driverDisbursement: {
    label: t`司机垫付费用`,
  },
  fleetSettlement: {
    label: t`公司结算状态`,
    text: (v) => (v ? t`已结算` : t`未结算`),
  },
  driverSettlement: {
    label: t`司机结算`,
    text: (v) => (v ? t`已结算` : t`未结算`),
  },
  orderSettlement: {
    label: t`下单人后付费用是否结算`,
  },
  cancelTime: {
    label: t`取消时间`,
    text: DATETIME_TEXT,
  },
  completionTime: {
    label: t`完成时间`,
  },
  companySettlementId: {
    label: t`公司结算id`,
  },
  driverSettlementId: {
    label: t`司机结算id`,
  },
  closingOfDistribution: {
    label: t`是否分账结束`,
  },
  direction: {
    label: t`false-第一段任务 true-第二段任务`,
  },
  tickets: [
    {
      label: t`车票信息`,
      orderId: {
        label: t`订单id`,
      },
      ticketCode: {
        label: t`车票号`,
      },
      ticketPrice: {
        label: t`票价`,
      },
      shift: {
        label: t`班次id`,
      },
      fromStation: {
        label: t`上车站点`,
      },
      fromStationName: {
        label: t`上车站点名称`,
      },
      fromStationAddress: {
        label: t`详情地址`,
      },
      toStation: {
        label: t`下车站点`,
      },
      toStationName: {
        label: t`下车站点名称`,
      },
      shiftTime: {
        label: t`上车时间`,
        text: DATETIME_TEXT,
      },
      toStationAddress: {
        label: t`下车站点地址`,
      },
      writeOffDate: {
        label: t`上车时间`,
        text: DATETIME_TEXT,
      },
      state: {
        label: t`状态`,
        text: (v) => ENUMS.ticketState[v],
        //  0：未乘车，1：已乘车`,
      },
      passenger: {
        label: t`乘车人（平台用户username）`,
      },
      passengerName: {
        label: t`客户`,
        text: (_, record) => {
          const { passengerName, passengerPhone } = record;
          return `${passengerName} ${passengerPhone}`;
        },
      },
      passengerPhone: {
        label: t`乘车人电话`,
      },
    },
  ],
  accountRequestInfos: [
    {
      label: t`分账请求信息列表`,
      appId: {
        label: t`appId`,
      },
      id: {
        label: t`订单id`,
      },
      transactionId: {
        label: t`微信支付订单号`,
      },
      outOrderNo: {
        label: t`商户系统内部的分账单号`,
      },
      orderId: {
        label: t`微信分账单号,微信支付系统返回的唯一标识`,
      },
      state: {
        label: t`分账单状态（每个接收方的分账结果请查看receivers中的result字段）<br/> 1、PROCESSING：处理中<br/> 2、FINISHED：分账完成`,
      },
      receivers: [
        {
          label: t`分账方信息列表`,
          type: {
            label: t`分账接收方类型<br/> 1、MERCHANT_ID：商户号<br/> 2、PERSONAL_OPENID：个人openid（由父商户APPID转换得到）`,
          },
          description: {
            label: t`分账的原因描述，分账账单中需要体现`,
          },
          account: {
            label: t`分账接收方账号：<br/> 1、类型是MERCHANT_ID时，是商户号（mch_id或者sub_mch_id）<br/> 2、类型是PERSONAL_OPENID时，是个人openid`,
          },
          username: {
            label: t`合伙人 / 公司 / 司机`,
          },
          name: {
            label: t`合伙人名 / 公司名 / 司机`,
          },
          userType: {
            label: t`身份 1-合伙人 2-公司 3-司机`,
          },
          amount: {
            label: t`分账金额 单位为分，只能为整数，不能超过原订单支付金额及最大分账比例金额`,
          },
          result: {
            label: t`分账结果<br/> 1、PENDING：待分账<br/> 2、SUCCESS：分账成功<br/> 3、CLOSED：已关闭`,
          },
          failReason: {
            label: t`分账失败原因，当分账结果result为CLOSED（已关闭）时，返回该字段<br/> 1、ACCOUNT_ABNORMAL：分账接收账户异常<br/> 2、NO_RELATION：分账关系已解除<br/> 3、RECEIVER_HIGH_RISK：高风险接收方<br/> 4、RECEIVER_REAL_NAME_NOT_VERIFIED：接收方未实名<br/> 5、NO_AUTH：分账权限已解除<br/> 6、RECEIVER_RECEIPT_LIMIT：接收方已达收款限额<br/> 7、PAYER_ACCOUNT_ABNORMAL：分出方账户异常`,
          },
          detailId: {
            label: t`微信分账明细单号`,
          },
          inflowPlatform: {
            label: t`这笔资金是否放回平台`,
          },
          redistribute: {
            label: t`重新分账信息`,
            outOrderNo: {
              label: t`商户系统内部的分账单号`,
            },
            orderId: {
              label: t`微信分账单号,微信支付系统返回的唯一标识`,
            },
            state: {
              label: t`分账单状态（每个接收方的分账结果请查看receivers中的result字段）<br/> 1、PROCESSING：处理中<br/> 2、FINISHED：分账完成`,
            },
            result: {
              label: t`分账结果<br/> 1、PENDING：待分账<br/> 2、SUCCESS：分账成功<br/> 3、CLOSED：已关闭`,
            },
            failReason: {
              label: t`分账失败原因，当分账结果result为CLOSED（已关闭）时，返回该字段`,
            },
            detailId: {
              label: t`微信分账明细单号`,
            },
          },
        },
      ],
    },
  ],
  crBy: {
    label: t`创建者`,
  },
  upBy: {
    label: t`最后修改者`,
  },
  crDate: {
    label: t`创建时间`,
    text: DATETIME_TEXT,
  },
  upDate: {
    label: t`最后修收时间`,
  },
  tenantId: {
    label: t`租户ID`,
  },
  id: {
    label: t`任务编号`,
  },
  // 前端新增字段
  startArea: {
    label: t`上车站点`,
    text: (_, record) => {
      const { startMainAreaText, startStationName } = toJS(record.orderBaseModel) || {};
      const text = `${startMainAreaText}-${startStationName}`;
      return text;
    },
    ui: {
      renderer: (v, record) => {
        const { startMainAreaText, startStationName } = toJS(record.orderBaseModel) || {};
        const text = `${startMainAreaText}-${startStationName}`;
        return <>{text}</>;
      },
    },
  },
  endArea: {
    label: t`下车站点`,
    text: (_, record) => {
      const { endMainAreaText, endStationName } = toJS(record.orderBaseModel) || {};
      const text = `${endMainAreaText}-${endStationName}`;
      return text;
    },
    ui: {
      renderer: (_, record) => {
        const { endMainAreaText, endStationName } = toJS(record.orderBaseModel) || {};
        const text = `${endMainAreaText}-${endStationName}`;
        return <>{text}</>;
      },
    },
  },
  startMainAreaText: {
    label: t`上车站点`,
    text: (v, r) => {
      const { fromStationName } = r;
      return <>{`${v}-${fromStationName}`}</>;
    },
  },
  endMainAreaText: {
    label: t`下车站点`,
    text: (v, r) => {
      const { toStationName } = r;
      return <>{`${v}-${toStationName}`}</>;
    },
  },
  fromStationAddress: {
    label: t`开始地址`,
    ui: {
      span: 3,
    },
  },
  toStationAddress: {
    label: t`结束地址`,
    ui: {
      span: 3,
    },
  },
  shiftTime: {
    label: t`上车时间`,
    text: DATETIME_TEXT,
  },
  startRecord: {
    label: t`上车地点显示人数`,
    text: (v, r) => {
      const list = [];
      const { tickets = [] } = r || {};

      // 用于存储每个站点对的乘客数量
      const stationPairCounts = {};

      for (const item of tickets) {
        if (item.ticketCode) {
          const fromStation = item.fromStationName;
          // 统计每个站点对的乘客数量
          if (stationPairCounts[fromStation]) {
            stationPairCounts[fromStation]++;
          } else {
            stationPairCounts[fromStation] = 1;
          }
        }
      }
      // 将统计结果转换为所需的格式
      for (const [stationPair, count] of Object.entries(stationPairCounts)) {
        const [fromStation] = stationPair.split('-');
        list.push({
          fromStation,
          count,
        });
      }
      return (
        <>
          {list.map((item, index) => (
            <div key={index}>
              {`${item.fromStation} (${item.count}人)`}
            </div>
          ))}
        </>
      );
    },
  },
  endRecord: {
    label: t`下车地点显示人数`,
    text: (v, r) => {
      const list = [];
      const { tickets = [] } = r || {};

      // 用于存储每个站点对的乘客数量
      const stationPairCounts = {};

      for (const item of tickets) {
        if (item.ticketCode) {
          const toStation = item.toStationName;
          // 统计每个站点对的乘客数量
          if (stationPairCounts[toStation]) {
            stationPairCounts[toStation]++;
          } else {
            stationPairCounts[toStation] = 1;
          }
        }
      }
      // 将统计结果转换为所需的格式
      for (const [stationPair, count] of Object.entries(stationPairCounts)) {
        const [toStation] = stationPair.split('-');
        list.push({
          toStation,
          count,
        });
      }
      return (
        <>
          {list.map((item, index) => (
            <div key={index}>
              {`${item.toStation} (${item.count}人)`}
            </div>
          ))}
        </>
      );
    },
  },
  showPrice: {
    label: t`价格(公司/司机)`,
    text: (_, record) => {
      const { carrierPrice, driverServiceFee } = record;
      return t`${carrierPrice},${driverServiceFee}`;
    },
  },
  // 派车字段
  fullname: {
    label: t`司机`,
  },
  showCar: {
    label: t`承运车辆`,
    text: (_, record) => {
      const { mainland, hk } = record?.licenseNo;
      return `${mainland}(${hk})`;
    },
    ui_view: {
      renderer: (_, record) => {
        const { mainland, hk } = record?.licenseNo;
        return `${mainland}/${hk}`;
      },
      span: 2,
    },
  },
  // 变更字段
  arCarrierCompanyId: {
    label: t`公司id`,
  },
  arCarrierCompanyName: {
    label: t`公司名称`,
  },
  arCarrierCompanyPrice: {
    label: t`公司费用`,
    ui: {
      itemProps: {
        required: true,
      },
    },
  },
  ticketFlag: {
    label: t`是否核销出票`,
    ui: {
      renderer: (v) => <Switch checked={v} checkedChildren={t`是`} unCheckedChildren={t`否`} autoWidth />,
    },
  },
  sendFlag: {
    label: t`是否发送通知`,
    ui: {
      renderer: (v) => <Switch checked={v} checkedChildren={t`是`} unCheckedChildren={t`否`} autoWidth />,
    },
  },
  showDriver: {
    label: t`承运司机`,
    ui_view: {
      renderer: (_, record) => {
        const { fullname, phone } = record;
        return `${fullname} ${phone}`;
      },
      span: 2,
    },
  },
  sendCarOrderPrice: {
    label: t`派单价格`,
    ui_view: {
      renderer: (_, record) => {
        const { carrierPrice } = record?.taskInfo;
        return `¥${carrierPrice}`;
      },
      span: 4,
    },
  },
  orderRemark: {
    label: t`订单备注`,
    ui_view: {
      renderer: (_, record) => {
        const { remarks } = record?.orderInfo?.ccOrder || {};
        return <span style={{ color: 'red' }}>{remarks || '无'}</span>;
      },
      span: 4,
    },
  },
  driverServiceFee: {
    label: t`司机费用`,
    ui_edit: {
      renderer: (v) => <Input value={v} placeholder={t`请输入司机费用`} />,
      span: 4,
      itemProps: { required: true, format: 'number' },
    },
  },

  // 编辑订单
  newOrders: {
    label: t`新订单`,
  },
  taskOrders: {
    label: t`任务中订单`,
  },
  attachments: {
    label: t`图片`,
    title: {
      label: t`图片标题`,
    },
    description: {
      label: t`图片说明`,
    },
    binaryId: [
      {
        label: t`图片id`,
      },
    ],
  },
  driverPlate: {
    label: t`司机车牌`,
    text: (v, record) => {
      let text = '';
      const res = rootStore.scTaskStore.getDriverInfo(record?.driverInfo) || {};
      if (Object.keys(res).length > 0) {
        const { name, licenseNo = '' } = res;
        const plates = licenseNo.split('/');
        text = `${name}(${plates[0]})`;
      }
      return <>{ellipsisRender(text)}</>;
    },
  },
  stationGroup: {
    label: t`上车/下车站点`,
    text: (v, record) => {
      const { tickets = [] } = toJS(record) || {};
      // const { startMainAreaText, endMainAreaText } = orderBaseModel;
      const resultTickets = [];
      const mapArr = new Map();
      tickets.forEach((p) => {
        if (!mapArr.has(`${p.fromStationName}:${p.toStationName}`)) {
          mapArr.set(`${p.fromStationName}:${p.toStationName}`, true);
          resultTickets.push(p);
        }
      });
      const lines = (({ fromStationName, toStationName }) => (
        <>
          <div>{ellipsisRender(`${fromStationName}`)}</div>
          <div>{ellipsisRender(`～${toStationName}`)}</div>
        </>
      ));
      return resultTickets.map(lines);
    },
  },

  // 中港通出票
  startMainArea: {
    label: t`开始城市编号`,
  },
  startMinorArea: {
    label: t`始发站点`,
    ui: {
      renderer: (v) => <TauSimpleSelect value={v} placeholder={t`请选择开始站点`} showSearch data={rootStore.scTaskStore.startStations} />,
      itemProps: { required: true },
    },
  },
  startStationName: {
    label: t`开始站点名称`,
  },
  endMainArea: {
    label: t`结束城市编号`,
  },
  endMinorArea: {
    label: t`结束站点`,
    ui: {
      renderer: (v) => <TauSimpleSelect value={v} placeholder={t`请选择结束站点`} showSearch data={rootStore.scTaskStore.endStations} />,
    },
  },
  endStationName: {
    label: t`结束站点名称`,
  },
  serviceShift: {
    label: t`班次`,
    ui: {
      renderer: (v) => <TauSimpleSelect value={v} placeholder={t`请选择班次`} showSearch data={rootStore.scTaskStore.shifts} />,
    },
  },
  noticeUser: {
    label: t`通知人`,
    ui: {
      renderer: (v) => <TauSimpleSelect value={v} placeholder={t`请选择短信通知人`} showSearch data={rootStore.scTaskStore.noticeUsers} />,
    },
  },
  ZGTTakeTicket: {
    label: t`是否中港通出票`,
    ui: {
      renderer: (v) => (
        <Switch
          checked={v}
          checkedChildren={t`是`}
          unCheckedChildren={t`否`}
          autoWidth
          size="small"
        />
      ),
    },
  },
};
